/* eslint-disable */
// import Cookies from 'js-cookie'
// import qs from 'qs'
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
// Please ASK KEN to REVIEW code change if you need MODIFY this file
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
import Vue from 'vue'
import * as Echarts from 'echarts'
import MoreMenu from '@/components/gadget-more-menu/index'
import DrillThrough from '@/components/gadget-drill-through/index'
import {
  formatDataList
} from '@/utils/common'
import GenerateBot from '@/components/gadget-generate-bot/index'
import {
  slicerGadgetTypeList
} from '@/utils/data-json'

import Emitter from '@/mixins/emitter'
import { get } from 'lodash'

import DashboardInterceptConsumer from '@/components/storybook/s-Intercept/dashboard-intercept-consumer'
import {getIntegrationCodes} from '@/components/storybook/utilties/flatIntegration'
import Pagination from '@/components/pagination/index'
import { fetchWidgetInfo } from '@/api/new'
export default {
  components: {
    MoreMenu,
    DrillThrough,
    GenerateBot,
    DashboardInterceptConsumer,
    Pagination
  },
  mixins: [Emitter],
  props: {
    pageId: {
      type: String,
      default: 'pvtable-gadget'
    },
    fitToHeight: {
      type: Boolean,
      default: false
    },
    zoomNumber:{
     type:Number,
     default:1
    },
    editMode: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    gadgetInfo: {
      type: Object,
      default: null
    },
    dataInfo: {
      type: Object,
      default: () => ({})
    },
    businessType: {
      type: String,
      default: ''
    },
    reportNameForPage: {
      type: String,
      default: ''
    },
    layoutType: {
      type: String,
      default: ''
    },
    loadingStatus: {
      type: Boolean,
      default: false
    },
    presentMode: {
      type: Boolean,
      default: false
    },
    presentModeItem: {
      type: Boolean,
      default: false
    },
    errorStatus:{
      type: String,
      default: ''
    },
    pageFrom: {
      type: String,
      default: ''
    },
    pageFromType: {
      type: String,
      default: ''
    },
    autoFull: {
      type: Boolean,
      default: false
    },
    rolHeight: {
      type: [String,Number],
      default: 10
    },
    comPageWidth: {
      type: [String,Number],
      default: 790
    },
    startIndex: {
      type: [String,Number],
      default: '0'
    },
    endIndex: {
      type: [String,Number],
      default: '0'
    },
    name: String,
    peerGroupId: String
  },
  data () {
    return {
      gadgetHeight: 0,
      gadgetWidth: 0,
      gadgetStatus: 'ready',
      gadgetType: '',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id
        }
      },
      isHasData: false,
      noDataImageUrl: this.$ossLink + '/app/gadget/gadget_no_data.jpg',
      filterType: '',
      messageType: '',
      refreshCount: 0,
      autoRefreshAwaitTime: 1000,
      pageConfig: {
        pageSize:50,
        total:0,
        current:1,
        gadgetType:'',
        pages: 0
      }
    }
  },
  inject:{
    gadgetMessageBus:{
      default:()=>new Vue()
    },
    getSlicer:{
      default:()=>{}
    },
    clonable:{
      default:undefined
    },
    getFilters:{
      default:()=>{}
    },
    gadgetInfos:{
      default:()=>{}
    },
    getSlicerComponents:{
      default:()=>[]
    },
    getGadgetLoadingStatus:{
      default:()=>[]
    },
    isQueryModel:{
      default:false
    },
    dashboardsDetailsData:{
      default:()=>{}
    },
    popperAppendToBody:{
      default:true
    },
    getThemeSetting:{
      default:()=>{}
    },
    getTheme: {
      default: ()=>'white'
    },
  },
  created () {
    if (this.isQueryModel&&this.isQueryModel()) {
      this.filterType = 'widget'
    } else {
      this.filterType = 'gadget'
    }
    try{
      this.autoRefreshAwaitTime = Number(window.SITE_CONFIG['dictList'].find(e => e.dictType === 'auto_refresh_await_time').dataList[0].dictValue) || 1000
    } catch (e) {
      this.autoRefreshAwaitTime = 1000
    }
  },
  watch:{
    globalTheme(){
      if(this.chartDom ){
        this.chartDom&&Echarts.init(this.chartDom).dispose()
        
        this.updateChart(this.queryData)
      }
    },
  },
  computed: {
    globalTheme(){
      if(typeof this.getTheme === 'function'){
        const theme = this.getTheme()
        return theme ===  'white' ? null: theme
      }
    },
    clientPortalUser(){
      return this.$store.state.user.regSource === '3'
    },
    slicer () {
      return this.getSlicer()
    },
    filters () {
      return this.getFilters()
    },
    code () {
      return  getIntegrationCodes(this.gadgetInfo.integrationList || this.dataInfo.integrationCode)
    },
    wgadgettype () {
      return this.gadgetInfo.com || this.dataInfo.gadgetType
    },
    wName () {
      return this.dataInfo.name || this.gadgetInfo.name
    },
    appId () {
      return get(this.$route, 'query.appId')
    },
    widgetNoDataWiki(){
      let temp = {}
      const wikiInfoList = window.SITE_CONFIG['wikiInfo'] || []
      temp = wikiInfoList.find(item=>item.key==="widgetNoDataWiki")
      const wikiUrl = temp &&temp.url?temp.url:'https://wiki.mspbots.ai/pages/viewpage.action?pageId=35688703'
      return wikiUrl
    },
    fontSizeStr1(){
      let fontSizeStr1 = ''
      if(this.gadgetInfo&&this.gadgetInfo.h&&this.gadgetInfo.w) {
        fontSizeStr1 =(this.gadgetInfo.h*this.gadgetInfo.w)/8
        if(fontSizeStr1&&fontSizeStr1>30) {
          fontSizeStr1 ="30px"
        } else if(fontSizeStr1&&fontSizeStr1<14) {
          fontSizeStr1 ="14px"
        } else {
          fontSizeStr1 =(this.gadgetInfo.h*this.gadgetInfo.w)/8+'px'
        }
      } else {
        fontSizeStr1="14px"
      }
      return fontSizeStr1
    },
    fontSizeStr2(){
      let fontSizeStr2 = ''
      if(this.gadgetInfo&&this.gadgetInfo.h&&this.gadgetInfo.w) {
        fontSizeStr2 =(this.gadgetInfo.h*this.gadgetInfo.w)/10
        if(fontSizeStr2&&fontSizeStr2>25) {
          fontSizeStr2 ="25px"
        } else if(fontSizeStr2&&fontSizeStr2<12) {
          fontSizeStr2 ="12px"
        } else {
          fontSizeStr2 =(this.gadgetInfo.h*this.gadgetInfo.w)/10+'px'
        }
      } else {
        fontSizeStr2="12px"
      }
      return fontSizeStr2
    },
    getThemeSetting () {
      return this.getThemeSetting()
    }
  },

  beforeMount () {
    this.updateGadgetStatus(this.gadgetStatus)
  },
  beforeDestroy () {
    this.gadgetMessageBus.$off(this.pageId + this.messageType)
  },
  methods: {
 
    autoRefreshQuery(e) {
      if (e === 'auto') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
        }, this.autoRefreshAwaitTime)
      } else {
        this.loading = false
      }
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 260
      this.gadgetWidth = newWPx
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {

    },
    updateGadgetStatus (status) {
      try {
        const gadgetInfos = this.gadgetInfos()
        if (gadgetInfos || gadgetInfos.length > 0) {
          this.gadgetStatus = status
          var index = this._.findIndex(gadgetInfos, {
            'id': this.id
          })
          if (index >= 0) {
            this.gadgetInfos()[index].gadgetStatus = this.gadgetStatus
          }
          // check if all gadget is ready

          index = this._.findIndex(gadgetInfos, {
            'gadgetStatus': 'init'
          })
          if (index === -1) {
            this.publishMessage('GadgetsReady')
            this.publishMessage('runReport')
          }
        }
      } catch (error) { }
    },
    updateGadgetLoadingStatus (status) {
      try {
        if (this.getGadgetLoadingStatus() || this.getGadgetLoadingStatus().length > 0) {
          var index = this._.findIndex(this.getGadgetLoadingStatus(), {
            'id': this.id
          })
          if (index >= 0 && !this.getGadgetLoadingStatus()[index].loadingStatus) {
            this.getGadgetLoadingStatus()[index].loadingStatus = status
          }
          index = this._.findIndex(this.getGadgetLoadingStatus(), {
            'loadingStatus': false
          })
          if (index === -1) {
            this.$root.eventBus.$emit('gadgetLoadingStatusCheck')
          }
        }
      } catch (error) { }
    },
    saveGadgetSetting () {

    },
    loadGadgetSetting () {

    },
    upgradeGadgetSetting () {

    },
    generateGadgetSetting () {

    },
    queryModelPreview () {
      this.query()
    },
    mappingFormSetting (to, from) {
      return this._.merge(to, from)
    },
    publishMessage (messageType, message,type) {
      this.gadgetMessageBus.$emit(this.pageId + messageType, message,type)
    },
    subscribeMessage (messageType, callback) {
      this.messageType = messageType
      this.gadgetMessageBus.$on(this.pageId + messageType, (e,type) => {
        if (e === 'resetRefresh') {
          this.refreshCount = 0
        }
        callback(e,type)
        if (this.pageId === 'home') {
          this.gadgetMessageBus.$off(this.pageId + messageType)
        }
      })
    },
    mouseenter (isEnter) {
      this.publishMessage('mouseevent', isEnter)
    },
    delDadget (id) {
      this.$confirm(this.$t('prompt.info', {
        'handle': this.$t('delete')
      }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.publishMessage('delDadget', id)
      }).catch(() => { })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    verifyHasData (res) {
      // this.isHasData = false
      if(res&&res.businessType) {

        this.gadgetInfo.businessType = res.businessType
      }
      if (res.code !== 0 || !res.data || res.data.length === 0) {
        this.isHasData = false
        // if (res.code !== 0) {
        //   return this.$message.error(res.msg)
        // }
      } else {
        this.isHasData = true
      }
    },
    findOriginData (data) {
      if (this.gadgetSetting.drillThrough && this.gadgetSetting.drillThrough.status && this.gadgetSetting.drillThrough.pageid) {
        // let url = this.gadgetSetting.drillThrough.url
        // try {
        //   if (url.substring(0, 4) === 'http') {
        //     window.open(url, '_blank')
        //   } else {
        //     this.$router.push({
        //       path: url,
        //       query: { ...this.gadgetSetting.drillThrough.data, ...this.slicer }
        //     })
        //   }
        // } catch (error) { }
        this.$store.state.drillThrough.pageid = this.gadgetSetting.drillThrough.pageid + ''
        this.$store.state.drillThrough.data = {
          ...this.gadgetSetting.drillThrough.data,
          ...this.slicer
        }
        this.$nextTick(() => {
          this.queryModelDefaultSetting.dataInfo.businessId = this.$store.state.drillThrough.pageid
          this.$store.state.drillThrough.dialogStatus = true
        })
      } else {
        if (this.gadgetSetting.drillThroughStatus) {
          this.$refs['drill-through'].init(data)
        }
      }
    },
    clearFilter () {
      this.filters.length = 0
    },
    addFilter (gadgetid, filter) {
      let item = this._.find(this.filters, {
        'slicerid': this.id,
        'gadgetid': gadgetid
      })
      if (item && item.length !== 0) {
        item.filter = filter
      } else {
        if (this.filters) {
          this.filters.push({
            slicerid: this.id,
            gadgetid: gadgetid,
            filter: filter
          })
        }
      }
    },
    getFilterStr () {
      let selectedFilter = this._.filter(this.filters, ['gadgetid', this.id])
      let condition = ''
      if (selectedFilter) {
        for (let i = 0; i < selectedFilter.length; i++) {
          if (i === selectedFilter.length - 1) {
            condition += selectedFilter[i].filter
          } else {
            condition += selectedFilter[i].filter + ' and '
          }
        }
      }
      return condition
    },
    formatData (data, selectFields, gadgetType) {
      return formatDataList(data, selectFields, 'bind', gadgetType)
    },
    returnReportLinkParam () {
      try {
        let qureObj = {}
        let hasQure = decodeURIComponent(window.location.search).split('?').length > 1
        hasQure && decodeURIComponent(window.location.search).split('?')[1].split('&').map(e => { qureObj[e.split('=')[0]] = `${e.split('=')[1]}` })
        if (qureObj.pageid) {
          delete qureObj.pageid
        }
        return qureObj
      } catch (error) { }
    },
    isFullScreen() {
      return  !!document.getElementsByClassName('fullScreenDialog')[0]
    },
    fullScreen (){
      if(this.id){
        if(!this.isFullScreen()){
          this.$emit('fullScreen',{id:this.id,type:'in'})
          // setTimeout(() => {
          //   this.$nextTick(()=>{
          //     this.gadgetHeight=window.screen.height
          //     this.gadgetWidth=window.screen.width-50
          //     if(this.wgadgettype==='scorecardgadget'){
          //       this.$nextTick(() => {
          //         if (this.chartDom) {
          //           let myChart = Echarts.init(this.chartDom, this.globalTheme)
          //           myChart.resize({
          //             width: this.gadgetWidth * 0.94,
          //             height: this.gadgetHeight - 30 * 2 - 34 - 30
          //           })
          //         }
          //       })
          //     }
          //   })
          // }, 0);
        }else{
          this.$emit('fullScreen',{id:this.id,type:'out'})
          // setTimeout(() => {
          //   this.$nextTick(()=>{
          //     this.gadgetHeight = this.pageFromType === 'report' ? ((this.gadgetInfo.h * this.rolHeight) - 45) : this.pageFrom === 'reportLayout' ? ((this.gadgetInfo.h * 20) - 45) : ((this.gadgetInfo.h * 23) - 45)
          //     this.gadgetWidth = this.pageFromType === 'report' ? ((this.gadgetInfo.w * this.comPageWidth/12)) : (this.gadgetInfo.w * 7) * 19
          //   })
          // }, 0);
        }
      }
    },
    async getWidgetInfo (gadgetId) {
      const params = {
        gadgetId,
        includeSql: true
      }
      const { data: response } = await fetchWidgetInfo(params)
      if (response.code !== 0) {
        return {}
      }
      return response.data || {}
    },
  }
}
